package com.example.sneakerappforme1105.orderFragment;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;

import com.example.sneakerappforme1105.DTO.OrderPostData;
import com.example.sneakerappforme1105.DataProvider;
import com.example.sneakerappforme1105.GoodsDetailActivity;
import com.example.sneakerappforme1105.MainApplication;
import com.example.sneakerappforme1105.PaymentActivity;
import com.example.sneakerappforme1105.R;
import com.example.sneakerappforme1105.adapter.OrderAdapter;
import com.example.sneakerappforme1105.bean.BackendGoods;
import com.example.sneakerappforme1105.bean.Goods;
import com.example.sneakerappforme1105.bean.Order;
import com.example.sneakerappforme1105.bean.OrderItem;
import com.example.sneakerappforme1105.constant.NetConst;
import com.example.sneakerappforme1105.dao.GoodsDao;
import com.example.sneakerappforme1105.dao.OrderDao;
import com.example.sneakerappforme1105.dao.OrderItemDao;
import com.example.sneakerappforme1105.util.ToastUtil;
import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import com.google.gson.reflect.TypeToken;

import java.io.IOException;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import c.t.m.g.e;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class AllOrderFragment extends Fragment {
    String TAG = "AllOrderFragment";
    protected View mView;
    protected AppCompatActivity mActivity;
    private RecyclerView rv_allorder;
    private Long mUserId;   // 得传入订单
    private HashMap<Long, Goods> mGoodsMap = new HashMap<>(); // long 是info.goodsId作为外键
    private List<Order> mList = new ArrayList<>();  // 所有的订单
    private HashMap<Long, List<OrderItem>> map = new HashMap<>();// 订单id->所有的订单项
    private OrderDao orderDao;
    private GoodsDao goodsDao;
    private OrderItemDao orderItemDao;
    private OrderAdapter orderAdapter;


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        DataProvider dataProvider = (DataProvider) getActivity();   // 用来得到 所挂载活动的成员变量
        mView = inflater.inflate(R.layout.fragment_allorder, container, false);
        mActivity = (AppCompatActivity) getActivity();
        orderDao = MainApplication.getInstance().getAppDatabase().orderDao();
        orderItemDao = MainApplication.getInstance().getAppDatabase().orderItemDao();
        goodsDao = MainApplication.getInstance().getAppDatabase().goodsDao();
        rv_allorder = mView.findViewById(R.id.rv_allorder);
        if (dataProvider != null) {
            Log.d(TAG, "dataProvider不为空");
            mUserId = dataProvider.getUserId();
            mGoodsMap = dataProvider.getGoodsMap(); // 从挂载的Show_order中拿到

        }else{
            List<Goods> goodsList = goodsDao.queryAllGoods();
            for(Goods g: goodsList){
                mGoodsMap.put(g.getGoodsId(), g);
            }
        }


        // 11.23 根据 http请求订单
//        fetchAllOrders(mUserId);   // 根据userId来获取


        // 根据userId查询所有订单  本地数据库查询
//        mList = orderDao.queryAllOrderByUserId(mUserId);
//        for(Order i: mList){
//            List<OrderItem> itemList = orderItemDao.getOrderItemsByOrderId(i.getOrderId());// 查询对应订单下面所有的订单项
//            map.put(i.getOrderId(),itemList);   // 所有订单对应的订单项
//        }


        orderAdapter = new OrderAdapter(mActivity, mList, map, mGoodsMap);
        LinearLayoutManager llm = new LinearLayoutManager(mActivity);
        rv_allorder.setLayoutManager(llm);
        rv_allorder.setAdapter(orderAdapter);

        orderAdapter.setButtonListener(new OrderAdapter.OnButtonListener() {
            @Override
            public void onButtonClick(View view, int position) {
                // 重写方法 和 结算是一样的，不过订单以及存在于后端数据库
                Order o = mList.get(position); // 获取当前订单
                String cost = GoodsDetailActivity.formatDouble(o.getTotalAmount()); // 获取当前订单金额

                OkHttpClient client = new OkHttpClient();
                String BASE_URL = null;
                long orderId = o.getOrderId();
                System.out.println("订单号为" + (100000 + o.getOrderId()));
                BASE_URL = "http://172.20.10.12:8080/alipay/pay?subject=" + 123456 + "&traceNo=" + (100000 + orderId) + "&totalAmount=" + cost;

                Request request = new Request.Builder()
                        .url(BASE_URL)
                        .get()
                        .build();

                client.newCall(request).enqueue(new Callback() {
                    @Override
                    public void onFailure(@NonNull Call call, @NonNull IOException e) {
                        System.err.println("支付请求失败: " + e.getMessage());
                    }

                    @Override
                    public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException {
                        if (response.isSuccessful()) {
                            // 获取支付页面表单
                            String responseBody = response.body().string();
                            System.out.println("支付页面表单: \n" + responseBody);

                            mActivity.runOnUiThread(() -> {
                                Intent intent = new Intent(getContext(), PaymentActivity.class);
                                intent.putExtra("paymentHtml", responseBody);
                                intent.putExtra("orderId",orderId);
                                startActivity(intent);
                            });


                        } else {
                            System.err.println("支付请求失败: " + response.message());
                        }
                    }
                });  // get 请求完毕

                onPaymentSuccess(); // 更新库存


            }

        });

        orderAdapter.setDeleteListener(new OrderAdapter.OnDeleteListener() {
            @Override
            public void delete(View view, int position) {
                // 获取当前订单对象
                Order order = mList.get(position);
                long orderId = order.getOrderId();

                // 创建对话框
                AlertDialog.Builder builder = new AlertDialog.Builder(mActivity);
                builder.setTitle("删除订单")
                        .setMessage("确定要删除该订单吗？")
                        .setPositiveButton("确定", (dialog, which) -> {
                            // 点击确定后发送删除请求
                            deleteOrder(orderId, position);
                        })
                        .setNegativeButton("取消", (dialog, which) -> {
                            // 点击取消，关闭对话框
                            dialog.dismiss();
                        })
                        .show();
            }
        });

        // 11.23 根据 http请求订单
        fetchAllOrders(mUserId);   // 根据userId来获取,这里应该会重写请求
        return mView;
    }


    @Override
    public void onResume() {
        super.onResume();
        Log.d(TAG,"片段重启");

        fetchAllOrders(mUserId);    // 重新获得订单数据
    }

    private void fetchAllOrders(Long mUserId) {
        OkHttpClient client = new OkHttpClient();

        Request request = new Request.Builder()
                .url(NetConst.HTTP_PREFIX + "order/" + mUserId)  // pathvariable
                .get()
                .build();


        client.newCall(request).enqueue(new Callback() {

            @Override
            public void onFailure(@NonNull Call call, @NonNull IOException e) {

                System.out.println("请求订单错误！");
                mActivity.runOnUiThread(()->{
                    mList.clear();
                    map.clear();
                    // 从本地数据库加载订单
                    List<Order> localOrders = orderDao.queryAllOrderByUserId(mUserId);
                    for (Order order : localOrders) {
                        mList.add(order);
                        List<OrderItem> orderItems = orderItemDao.getOrderItemsByOrderId(order.getOrderId());
                        map.put(order.getOrderId(), orderItems);  // 从本地数据库加载关联的订单项
                    }
                    orderAdapter.notifyDataSetChanged();
                });
            }

            @Override
            public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException {
                if (response.isSuccessful()) {



                    String responseData = response.body().string();

                    Gson gson = new Gson();


                    JsonObject jsonObject = gson.fromJson(responseData, JsonObject.class);


                    JsonArray dataArray = jsonObject.getAsJsonArray("data");

                    Type orderType = new TypeToken<List<OrderPostData>>() {
                    }.getType();
                    List<OrderPostData> orderPostDataList = gson.fromJson(dataArray, orderType); // 得到所有的订单以及订单项



                    // 更新 UI
                    mActivity.runOnUiThread(() -> {
                        mList.clear();  // 清除之前的数据
                        map.clear();    // 清除之前的数据
                        orderAdapter.notifyDataSetChanged();
                        for (OrderPostData orderPostData : orderPostDataList) {
                            Order order = orderPostData.getOrder();
                            List<OrderItem> orderItems = orderPostData.getOrderItems();

                            mList.add(order);   // 当前该用户的所有订单
                            map.put(order.getOrderId(), orderItems);    // 订单关联的订单项
                        }
                        orderAdapter.notifyDataSetChanged();

                    });
                }
            }


        });

    }


    private void onPaymentSuccess() {
        OkHttpClient client = new OkHttpClient();

        Request request = new Request.Builder()
                .url(NetConst.HTTP_PREFIX + "goods/all")  // get请求
                .build();


        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(@NonNull Call call, @NonNull IOException e) {
                System.out.println("请求图片数据失败!");
            }

            @Override
            public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException {
                if (response.isSuccessful()) {
                    System.out.println("请求图片数据!");
                    String jsonResponse = response.body().string();
                    Gson gson = new Gson();



                    JsonObject jsonObject = gson.fromJson(jsonResponse, JsonObject.class);


                    JsonArray dataArray = jsonObject.getAsJsonArray("data");

                    Type listType = new TypeToken<List<BackendGoods>>() {
                    }.getType();
                    List<BackendGoods> backendGoodsList = gson.fromJson(dataArray, listType);

                    mActivity.runOnUiThread(() -> {
                        for (BackendGoods g : backendGoodsList) {
                            Goods goods = goodsDao.queryGoodsByGoodsId(g.getGoodsId());
                            goods.setCapcity(g.getCapcity());
                            goodsDao.updateGoods(goods);    // 更新本地商品库存
                        }
                    });


                }
            }
        });
    }


    private void deleteOrder(long orderId, int position) {
        OkHttpClient client = new OkHttpClient();


        String url = NetConst.HTTP_PREFIX+"order/" + orderId;

        Request request = new Request.Builder()
                .url(url)
                .delete()
                .build();


        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(@NonNull Call call, @NonNull IOException e) {
                // 请求失败
                Log.e("DeleteOrder", "删除订单失败：" + e.getMessage());
                mActivity.runOnUiThread(() -> ToastUtil.show(mActivity, "删除订单失败，请重试"));
            }

            @Override
            public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException {
                if (response.isSuccessful()) {
                    // 删除成功，从列表中移除
                    mActivity.runOnUiThread(() -> {
                        Order o = mList.get(position);
                        mList.remove(position); // 移除订单
                        orderDao.deleteOrderByOrderId(o.getOrderId());
                        orderAdapter.notifyItemRemoved(position); // 刷新 RecyclerView
                        ToastUtil.show(mActivity, "删除订单成功");
                    });
                } else {
                    // 请求失败，显示错误信息
                    Log.e("DeleteOrder", "删除订单失败：" + response.message());
                    mActivity.runOnUiThread(() ->
                            ToastUtil.show(mActivity, "删除订单失败，请重试")
                    );
                }
            }
        });
    }



}
